package com.wangyk.pay.service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wangyk.pay.pojo.weChatPayPojo.UnifyOrderRequest;
import com.wangyk.pay.pojo.weChatPayPojo.UnifyOrderResp;
import com.wangyk.pay.service.WeChatPayService;
import com.wangyk.pay.util.*;
import com.wangyk.rabbitmqcommon.VO.ResultVO;
import com.wangyk.rabbitmqcommon.utils.ResultVOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class WeChatPayServiceImpl implements WeChatPayService
{
    private Logger logger = LogManager.getLogger(WeChatPayServiceImpl.class);
    
    @Value("${appid}")
    private String APPID;
    
    @Value("${appsecret}")
    private String APPSECRET;
    
    @Value("${mch_id}")
    private String MCHID;
    
    @Value("${key}")
    private String KEY;
    
    @Value("${app_notify_url}")
    private String NOTIFYURL;
    
    @Value("${ip}")
    private String IP;
    
    @Value("${weixin_pay_url}")
    private String requestUrl;
    
    @Override
    public ResultVO wechatPay(Integer weixinId, UnifyOrderRequest unifyOrderRequest)
    {
        ResultVO resultVO = new ResultVO();
        try
        {
            String openId = "weixin_openid";
            logger.error("查询的openId" + openId);
            unifyOrderRequest.setOpenid(openId);
            // 设置openId
            // unifyOrderRequest.setOpenid("oH99Av3I_yWOB6i2SXFbE3eQqfWU");
            // 订单号，用来查询订单
            String orderNo = unifyOrderRequest.getOut_trade_no();
            // 根据订单号查询orders
            Object object=new Object();
            // 如果订单为null
            if (ObjectUtils.isEmpty(object))
            {
                return ResultVOUtils.error();
            }
            // 如果订单已支付
            if (false)
            {
                return ResultVOUtils.error();
            }
            // 订单号，用来生成参数
            // String orderNoReq = unifyOrderRequest.getOut_trade_no() + System.currentTimeMillis();
            unifyOrderRequest.setOut_trade_no(orderNo);
            // 返回给前台调用的数据
            UnifyOrderResp unifyOrderResp = new UnifyOrderResp();
            // 下一步操作
            logger.debug("订单号：" + orderNo);
            
            // unifyOrderRequest.setTotal_fee((int)(order.getOrderAmount() * 100));
            unifyOrderRequest.setTotal_fee(1);
            logger.debug("total_fee:" + unifyOrderRequest.getTotal_fee());
            logger.debug("前台传过来的对象：" + unifyOrderRequest);
            // 设置好参数对象
            setUnifyOrderReq(unifyOrderRequest);
            // 将对象转化为xml字符串
            String xmlString = unifyOrderToXml(unifyOrderRequest);
            logger.debug("将对象转化为xml字符串:" + xmlString);
            // 调用统一下单
            String response = HttpsRequestUtil.httpsRequest(requestUrl, "POST", xmlString);
            logger.debug("调用统一下单:" + response);
            // 解析返回的数据
            Map<String, String> respMap = MapAndXml.doXMLParse(response);
            // 查询
            String return_code = respMap.get("return_code");
            if (!"SUCCESS".equals(return_code))
            {
                return ResultVOUtils.error();
            }
            // 返回给前台调用的数据
            unifyOrderResp.setAppid(respMap.get("appid"));
            unifyOrderResp.setNonceStr(respMap.get("nonce_str"));
            unifyOrderResp.setPackAge("prepay_id=" + respMap.get("prepay_id"));
            unifyOrderResp.setSignType("MD5");
            unifyOrderResp.setTimeStamp(CreateSign.getTimeStamp());
            // 进行paySign签名
            SortedMap<Object, Object> paySignMap = new TreeMap<>();
            paySignMap.put("appId", unifyOrderResp.getAppid());
            paySignMap.put("timeStamp", unifyOrderResp.getTimeStamp());
            paySignMap.put("nonceStr", unifyOrderResp.getNonceStr());
            paySignMap.put("package", unifyOrderResp.getPackAge());
            paySignMap.put("signType", unifyOrderResp.getSignType());
            String paySignStr = CreateSign.createSign(paySignMap, KEY);
            unifyOrderResp.setPaySign(paySignStr);
            logger.debug("unifyOrderResp.getAppid():" + unifyOrderResp.getAppid());
            logger.debug("给前台的数据：" + unifyOrderResp);
            resultVO.setData(unifyOrderResp);
            return ResultVOUtils.success(resultVO);
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public ResultVO weiXinPay(UnifyOrderRequest req)
    {
        return null;
    }

    @Override
    public void weixinPaySuccess(HttpServletRequest request, HttpServletResponse response)
    {
        // TODO Auto-generated method stub
        try
        {

        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * @Description (参数初始化)
     * @author wangyk
     * @param unifyOrderReq
     */
    public void setUnifyOrderReq(UnifyOrderRequest unifyOrderRequest)
    {
        try
        {
            unifyOrderRequest.setAppid(APPID);
            unifyOrderRequest.setMch_id(MCHID);
            unifyOrderRequest.setNonce_str(CreateSign.getNonceStr());
            unifyOrderRequest.setBody("费用");
            // unifyOrderRequest.setTotal_fee(1);
            unifyOrderRequest.setSpbill_create_ip(IP);
            unifyOrderRequest.setNotify_url(NOTIFYURL);
            unifyOrderRequest.setTrade_type("JSAPI");
            // 签名算法开始
            SortedMap<Object, Object> signMap = new TreeMap<Object, Object>();
            signMap.put("appid", APPID);
            signMap.put("mch_id", MCHID);
            signMap.put("nonce_str", unifyOrderRequest.getNonce_str());
            signMap.put("body", unifyOrderRequest.getBody());
            signMap.put("total_fee", unifyOrderRequest.getTotal_fee());
            signMap.put("out_trade_no", unifyOrderRequest.getOut_trade_no());
            signMap.put("spbill_create_ip", unifyOrderRequest.getSpbill_create_ip());
            signMap.put("notify_url", unifyOrderRequest.getNotify_url());
            signMap.put("trade_type", unifyOrderRequest.getTrade_type());
            signMap.put("openid", unifyOrderRequest.getOpenid());
            unifyOrderRequest.setSign(CreateSign.createSign(signMap, KEY));
            // 签名算法结束
            logger.debug("第一次签名：" + unifyOrderRequest.getSign());
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
    }
    
    public String unifyOrderToXml(UnifyOrderRequest unifyOrderRequest)
    {
        try
        {
            Map<String, String> map = new HashMap<>();
            map.put("appid", unifyOrderRequest.getAppid());
            map.put("body", unifyOrderRequest.getBody());
            map.put("mch_id", unifyOrderRequest.getMch_id());
            map.put("nonce_str", unifyOrderRequest.getNonce_str());
            map.put("notify_url", unifyOrderRequest.getNotify_url());
            map.put("out_trade_no", unifyOrderRequest.getOut_trade_no());
            map.put("spbill_create_ip", unifyOrderRequest.getSpbill_create_ip());
            map.put("total_fee", unifyOrderRequest.getTotal_fee().toString());
            map.put("trade_type", unifyOrderRequest.getTrade_type());
            map.put("sign", unifyOrderRequest.getSign());
            map.put("openid", unifyOrderRequest.getOpenid());
            // 转化成xml格式字符串
            String xmlString = MapAndXml.GetMapToXML(map);
            return xmlString;
        }
        catch (Exception e)
        {
            logger.error(e.getMessage(), e);
        }
        return null;
    }
}
